package com.lc.reader.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.lc.reader.data.model.Book
import com.lc.reader.databinding.ItemBookBinding

class BookAdapter(
    private val onBookClick: (Book) -> Unit,
    private val onBookDelete: (Book) -> Unit
) : ListAdapter<Book, BookAdapter.BookViewHolder>(BookDiffCallback()) {
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookViewHolder {
        val binding = ItemBookBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return BookViewHolder(binding, onBookClick, onBookDelete)
    }
    
    override fun onBindViewHolder(holder: BookViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
    
    class BookViewHolder(
        private val binding: ItemBookBinding,
        private val onBookClick: (Book) -> Unit,
        private val onBookDelete: (Book) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {
        
        fun bind(book: Book) {
            binding.apply {
                textTitle.text = book.title
                textAuthor.text = book.author
                textFormat.text = book.format
                
                // 默认封面
                if (book.coverPath.isNullOrBlank()) {
                    imageCover.setImageResource(com.lc.reader.R.drawable.default_book_cover)
                } else {
                    imageCover.setImageResource(com.lc.reader.R.drawable.default_book_cover)
                }
                
                // 设置阅读进度
                val progress = (book.readingProgress * 100).toInt().coerceIn(0, 100)
                textProgress.text = "$progress%"
                progressBar.progress = progress
                
                // 点击事件
                root.setOnClickListener { onBookClick(book) }
                buttonDelete.setOnClickListener { onBookDelete(book) }
            }
        }
    }
    
    private class BookDiffCallback : DiffUtil.ItemCallback<Book>() {
        override fun areItemsTheSame(oldItem: Book, newItem: Book): Boolean {
            return oldItem.id == newItem.id
        }
        
        override fun areContentsTheSame(oldItem: Book, newItem: Book): Boolean {
            return oldItem == newItem
        }
    }
}
